package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName AlbumReceiver
 * @description: TODO
 * @date 2024年06月14日
 * @version: 1.0
 */
@Component
public class AlbumReceiver {


    @Autowired
    private AlbumInfoService albumInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 更新声音，专辑播放量
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String, String> record) {
        //  获取发送的消息
        String strJson = record.value();
        if (!StringUtils.isEmpty(strJson)) {
            //  将这个json 字符串转换为对象
            TrackStatMqVo trackStatMqVo = JSON.parseObject(strJson, TrackStatMqVo.class);
            //  业务编号：去重使用
            String businessNo = trackStatMqVo.getBusinessNo();
            //  第一次执行result = true;
            Boolean result = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 1, TimeUnit.DAYS);
            if (result) {
                //  更新播放量
                try {
                    albumInfoService.trackStatUpdate(trackStatMqVo);
                } catch (Exception e) {
                    //  如果有异常，则删除原有的key.
                    redisTemplate.delete(businessNo);
                    throw new RuntimeException(e);
                }
            }

        }
    }

}
